<template>
  <div class="preview-paper">
    <h3 class="paper-name">{{ name }}</h3>
    <h3 class="time">答题时间: {{ time }} 分钟</h3>
    <h3 class="time">用时: {{ pass }}</h3>
    <el-form class="list">
      <el-form-item class="item" v-for="(item, i) in subjects" :key="i">
        <h4 class="name">{{ i + 1 }}. {{ item.name }}</h4>
        <el-radio-group v-model="form[i]">
          <div v-for="(o, index) in item.options" :key="index" class="radio">
            <el-radio :disabled="disabled" :label="map[index]"
              >{{ map[index] }}: {{ o }}</el-radio
            >
          </div>
        </el-radio-group>
        <div
          v-if="completed"
          class="analysis e"
          :class="{ c: item.ans.toUpperCase() === form[i] }"
        >
          <div class="ans">你的答案: {{ form[i] }}</div>
          <div class="corr">正确答案是: {{ item.ans.toUpperCase() }}</div>
        </div>
      </el-form-item>
    </el-form>
    <div class="result fx item-c" v-if="completed">
      <div class="score">
        <span
          >你的得分: <span class="light">{{ score }}</span> 分</span
        >,
        <span>
          正确数: <span class="light">{{ ret.corr }}</span></span
        >,
        <span>
          错误数: <span class="light">{{ ret.err }}</span></span
        >,
        <span>
          用时:
          <span class="light">{{ minites }} 分钟 {{ second }} 秒</span></span
        >
      </div>
      <el-button @click="reset" size="large" type="primary">重做</el-button>
      <el-button @click="fallback" size="large" type="primary">返回</el-button>
    </div>
    <el-button
      v-if="!completed"
      type="primary"
      :loading="loading"
      @click="submit"
      size="large"
      >{{ msg }}</el-button
    >
  </div>
</template>

<script>
import { getOnePaper, addAnswer } from "@/api/paper";
import { formatSubjects, validate } from "@/utils";
import { info, success, warn, error } from "@/utils";
export default {
  data() {
    return {
      map: {
        0: "A",
        1: "B",
        2: "C",
        3: "D",
        4: "E",
        5: "F",
        6: "G",
        7: "H",
        8: "I",
        9: "J",
        10: "K",
      },
      name: "",
      subjects: [],
      form: [],
      ans: [],
      disabled: false,
      loading: false,
      msg: "提交试卷",
      completed: false,
      ret: {},
      passTime: "00: 00",
      second: 0,
      minites: 0,
      hours: 0,
      time: "",
      timer: "",
    };
  },
  computed: {
    score() {
      const piece = 100 / this.subjects.length;
      return (this.ret.corr * piece).toFixed(1);
    },
    // 计时
    pass() {
      return `${this.hours.toString().padStart(2, "0")}: ${this.minites
        .toString()
        .padStart(2, "0")}: ${this.second.toString().padStart(2, "0")}`;
    },
  },
  methods: {
    async getData(id) {
      const res = await getOnePaper(id);
      if (res.code === 1) {
        this.subjects = formatSubjects(res.data[0].subjects);
        this.form = new Array(this.subjects.length).fill(undefined);
        this.name = res.data[0].name;
        this.time = res.data[0].time;
        this.ans = this.subjects.map(
          (item) => item.id && item.ans.toUpperCase()
        );
      } else {
        error(res.msg);
      }
    },
    /**
     * 提交试卷
     */
    submit() {
      const no = [];
      this.form.forEach((item, i) => item === undefined && no.push(i + 1));
      if (no.length) {
        // 没做完
        return warn(
          `你还有 ${no.length} 道题没做完, 题号是 ${no.filter(
            (n) => typeof n === "number"
          )}`
        );
      } else {
        this.finish();
      }
    },
    /**
     * 重做
     */
    reset() {
      this.form = new Array(this.subjects.length).fill(undefined);
      this.completed = false;
      this.disabled = false;
      this.msg = "提交试卷";
    },
    /**
     * 评卷
     */
    async finish(force) {
      force && info("时间到了, 系统自动提交试卷");
      // 做完了
      this.loading = true;
      this.msg = "正在评卷中...";
      
      this.ret = validate(this.form, this.subjects);
      const paperId = this.paperId
      const time = this.minites + "分钟" + this.second + '秒' 
      const score = this.score
      const subjects = this.ret.ret

      const res = await addAnswer({paperId, time, score, subjects})

      clearInterval(this.timer);
      // 恢复loading
      this.loading = false;
      this.disabled = true;
      this.completed = true;
    },
    // 返回我的试卷
    fallback() {
      this.$router.back();
    },
  },

  created() {
    const { paperId } = this.$route.query;
    this.paperId = paperId
    this.getData(paperId);

    // 启动定时器
    this.timer = setInterval(() => {
      this.second++;
      if (this.second >= 60) {
        this.minites++;
        this.second = 0;
      }
      // 到达时间了, 交卷
      if (this.minites == this.time) return this.finish(true);
      if (this.minites >= 60) {
        this.hours++;
        this.minites = 0;
      }
    }, 1000);
  },
  destroyed() {
    clearInterval(this.timer);
  },

  /**
   * 离开页面
   */
  beforeRouteLeave(_, from, next) {
    if (
      !this.completed &&
      window.confirm("你确定要离开吗, 离开后不会对你的答卷进行保存")
    ) {
      next();
    } else {
      next();
    }
  },
};
</script>

<style scoped lang="scss">
.preview-paper {
  line-height: 1.5;
}

.paper-name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}

.name {
  font-size: 17px;
}

.item {
  margin: 20px 0;
}

.radio {
  margin: 15px 0;
}

.analysis.e {
  color: red;
}

.analysis.c {
  color: green;
}

.score {
  margin-right: 100px;
}

.light {
  color: #008c8c;
  font-weight: bold;
  font-size: 20px;
}

.time {
  font-weight: bold;
}
</style>
